import Axios from "./axios";
import store from "@/store";
import storage from "@/libs/storage";
import { logout } from "@/libs";
import router from "@/routes";

const excludeUrls = [
  "/shipping/get/deliverClass/list/export",
  "/shipping/get/deliver/list/export",
  "/shipping/get/deliverPoint/list/export",
  "/assemble/activity/ass/list/product_show_category",
  "/shipping/set/shipper/pointInfo",
];

const api = new Axios({
  baseURL: process.env.VUE_APP_BASEURL,
});

api.instance.interceptors.request.use(
  config => {
    if (config.headers && config.headers.type === "formData") {
      config.headers["Content-Type"] = "application/x-www-form-urlencoded"; // 模拟form表单方式提交请求
    } else {
      config.headers.Accept = "application/json";
    }
    config.headers.Contenttype = "application/json";
    config.headers.token = store.state.user.token || storage.get("token");
    config.headers.version = process.env.VUE_APP_APP_VERSION;
    // config.headers.tenantId = "100246";
    // config.headers.shopId = "100246100001";
    // config.headers.token =
    //   "platform:tk:eyJ0eXBlIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJqdGkiOiJjY2UwNzNlY2QwNjU0MzRjYjhjMmQ0YzYxOTIyN2MyZiIsInN1YiI6InBsYXRmb3JtIiwiaXNzIjoiYmduaWFvLmNvbSIsImlhdCI6MTYxMjQwMDYzNywiZXhwIjoxNjEyNDA3ODM3fQ.oCHq11KsLCkO5SNWaUW8Wph2czWB6L5OPzVub-uukQQ";
    if (store.state.user.userInfo && store.state.user.userInfo.shopInfoVo) {
      config.headers.shopId = store.state.user.userInfo.shopInfoVo.shopId;
      config.headers.tenantId = store.state.user.userInfo.shopInfoVo.tenantId;
    }
    // config.headers.tenantId = "9";
    // config.headers.shopId = "9";
    // config.headers.token = "platform:tk:f1b15b53a8abcff35c4d0faf6c97cc49j4renp4cdf57acb8a86cd11e981ada4cc0b747";
    return config;
  },
  err => {
    return Promise.reject(err);
  },
);

api.instance.interceptors.response.use(
  res => {
    if (res.data.code === 3) {
      logout();
      router.push("/sign").then(r => {
        console.log(r);
      });
    }
    if (excludeUrls.find(i => res.config.url.indexOf(i) !== -1)) {
      return res.data;
    } else if (res.data.code !== 200 || res.status !== 200) {
      return Promise.reject(
        res.data.msg || res.data.message || "未知错误，请稍后再试",
      );
    } else {
      return res.data;
    }
  },
  err => {
    return Promise.reject(err);
  },
);
export default api;
